const {
    router,
    Result,
    querySql,
    queryOne
} = require('../connect');
const md5 = require('../utils/md5');
const boom = require('boom');
const moment = require('moment');
const {
    body,
    validationResult
} = require('express-validator');
const {
    CODE_ERROR,
    CODE_SUCCESS,
} = require('../utils/constant');
const { setToken } = require('../token/token');

router.post('/login', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        let {
            username,
            password
        } = req.body;
        password = md5(password);
        const query = `select * from user where username='${username}' and password='${password}'`;
        querySql(query).then(user => {
            if (!user || user.length === 0) {
                res.json(new Result({
                    code: CODE_ERROR,
                    msg: '用户名或密码错误',
                    data: null
                }))
            } else {
                const userInfo = user[0]
                setToken(userInfo.username, userInfo.id).then(token => {
                    res.json(new Result({
                        code: CODE_SUCCESS,
                        msg: '登录成功',
                        data: {
                            token,
                            userData: userInfo
                        }
                    }))
                })



            }
        })

    }

})

// 通过用户名查询用户信息
function findUser(username) {
    const query = `select username from user where username='${username}'`;
    return queryOne(query);
}


router.post('/register', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        let {
            username,
            password,
            role,
            email,
            introduction
        } = req.body;

        findUser(username).then(data => {
            if (data) {
                res.json(new Result({
                    code: CODE_ERROR,
                    msg: '用户已存在',
                    data: null
                }))
            } else {
                password = md5(password);
                const createTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
                const query = `insert into user(username, password, role, email, introduction, createTime) 
                                values('${username}', '${password}', '${role}', '${email}', '${introduction}', '${createTime}')`;
                querySql(query).then(result => {
                    if (!result || result.lenght === 0) {
                        res.json(new Result({
                            code: CODE_ERROR,
                            msg: '注册失败',
                            data: null
                        }))
                    } else {
                        const queryUser = `select * from user where username='${username}' and password='${password}'`;
                        querySql(queryUser).then(user => {
                            const token = setToken(user.username, user.id)

                            res.json(new Result({
                                code: CODE_SUCCESS,
                                msg: '注册成功',
                                data: {
                                    token,
                                    userData: user
                                }
                            }))
                        })
                    }
                })
            }
        })
    }

})

router.delete('/delete', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        const {
            userId
        } = req.body;
        if (userId) {
            const sql = `delete from user where userId = '${userId}'`
            querySql(sql).then(result => {
                if (result.affectedRows === 1) {
                    res.json(new Result({
                        code: CODE_SUCCESS,
                        msg: '删除成功',
                        data: result
                    }))
                } else {
                    res.json(new Result({
                        code: CODE_ERROR,
                        msg: '删除失败',
                        data: null
                    }))
                }
            })
                .catch(err => {
                    throw err
                })
        } else {
            res.json(new Result({
                code: CODE_ERROR,
                msg: '删除失败，用户id为空',
                data: null
            }))
        }
    }
})

router.get('/logout', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        res.json(new Result({
            code: CODE_SUCCESS,
            msg: '退出成功',
            data: null
        }))
    }
})

const validateUser = (usernmae, password) => {
    const sql = `select userId, username from user where username='${usernmae}' and password='${password}'`
    return queryOne(sql);
}

router.post('/resetPwd', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        let {
            username,
            oldPassword,
            newPassword
        } = req.body;
        oldPassword = md5(oldPassword);
        newPassword = md5(newPassword);
        validateUser(username, oldPassword).then(isValidate => {
            if (isValidate) {
                const updateSql = `update user set password='${newPassword}' where username='${username}'`
                querySql(updateSql).then(user => {
                    if (!user || user.lenght === 0) {
                        res.json(new Result({
                            code: CODE_ERROR,
                            msg: '重置密码失败',
                            data: null
                        }))
                    } else {
                        res.json(new Result({
                            code: CODE_SUCCESS,
                            msg: '重置密码成功',
                            data: null
                        }))
                    }
                })
            } else {
                res.json(new Result({
                    code: CODE_ERROR,
                    msg: '用户名或者旧密码有误',
                    data: null
                }))
            }
        })
    }
})

router.post('/update', (req, res, next) => {
    const err = validationResult(req);
    // 如果验证出错，error不为空[]
    if (!err.isEmpty()) {
        // 获取错误信息
        const [{
            msg
            // @ts-ignore
        }] = err.errors;
        // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
        next(boom.badRequest(msg));
    } else {
        let {
            id,
            username,
            email,
            avator,
            introduction
        } = req.body;
        const updateSql = `UPDATE user set username='${username}',email='${email}',avatar='${avator}',introduction='${introduction}' WHERE userId=${id}`
        querySql(updateSql).then(() => {
            res.json(new Result({
                code: CODE_SUCCESS,
                msg: '修改成功',
                data: null
            }))
        })
            .catch((err) => {
                res.json(new Result({
                    code: CODE_ERROR,
                    msg: err,
                    data: null
                }))
            })
    }
})



router.get('/userinfo', (req, res) => {
    let params = req.query
    let sql = ''
    if (params.username == undefined || params.username == '') {
        sql = 'select * from user'
    } else {
        sql = 'select * from user  where username= ? and password=?'
    }

    let where_value = [params.username, params.password]
    querySql(sql).then(result => {
        res.json(new Result({
            data: result,
            code: 200
        }))
    })
})

module.exports = router;